package com.wantup.miaosha.config;

import com.wantup.miaosha.entity.TblUser;
import com.wantup.miaosha.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/6/5 17:35
 */
@Slf4j
@Component
public class UserArgumentResolvers implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> aClass = methodParameter.getParameterType();
        return aClass == TblUser.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {

        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeRequest(HttpServletResponse.class);

        String paramToken = request.getParameter("token");
        String cookieToken = getCookieValue(request, "token");


        if (StringUtils.isEmpty(cookieToken) || StringUtils.isEmpty(paramToken)) {
            return "login";
        }
        log.info("拦截方法中 cookie -->  " + cookieToken);
        log.info("拦截方法中 paramToken -->  " + paramToken);
        String token = StringUtils.isEmpty(paramToken) ? cookieToken : cookieToken;
        log.info("传入的值 --> token " + token);
        TblUser tblUser = this.userService.getUserByTokenService(token);
        return tblUser;
    }

    private String getCookieValue(HttpServletRequest request, String token) {
        Cookie[] cookies = request.getCookies();
        for (Cookie c : cookies) {
            if (c.getName().equals(token)) {
                return c.getValue();
            }
        }

        return null;
    }
}
